using System;
using System.Collections;
using System.Web.UI;
using System.Web.UI.WebControls;
using PHSRAG.Insight21.CDS;
using PHSRAG.Insight21.Common.Pages;
using PHSRAG.Insight21.FormsManagement;
using PHSRAG.Insight21.FormsManagement.Serialization;
using PHSRAG.Insight21.Policy;
using PHSRAG.Insight21.ScriptEngine;
using PHSRAG.Utility;
using ScriptReference = PHSRAG.Insight21.ScriptEngine.ScriptReference;

namespace PHSRAG.Insight21.COI
{
    /// <summary>
    /// This page is used to capture answers for a specified questionnaire
    /// </summary>
    public partial class COIAnswerQuestionnairePage : BasePage
    {
        #region Constants

        #endregion

        #region Instance Variables

        private ICachePolicy _applicationCachePolicy;
        private ICachePolicy _cachePolicy;
        private ConflictOfInterest _coi;
        private int _coiId;
        private ICachePolicy _pageCachePolicy;

        private QuestionnaireAnswer _questAnswer;
        private int _questionnaireAnswerId;
        private int _questionnaireVersionId;

        //This flag is used to decide whether or not the headers should be displayed
        //If the page is to be displayed as a popup, then the header section is made invisible
        private bool _showAsPopUp;
        private bool _AlertOnChangesToReOpenedAnnualCOI = false;

        #endregion

        #region Private properties

        /// <summary>
        /// Gets the COI object.
        /// If it's not already in the cache, it loads it up based on the coiId passed to the page, and caches the object
        /// </summary>
        private ConflictOfInterest CurrentConflictOfInterest
        {
            get
            {
                string cacheKey = ConflictOfInterest.COIKey;
                _coi = _cachePolicy.GetCachedObject(cacheKey) as ConflictOfInterest;

                if ((_coi == null) || (_coiId != _coi.Id))
                {
                    _coi = new ConflictOfInterest(_cachePolicy);
                    _coi.Load(DataAccess.GetConnectionString(), _coiId);
                    _cachePolicy.Cache(cacheKey, _coi);
                }
                return _coi;
            }
        }

        #endregion

        #region Page events

        /// <summary>
        /// Looks for a cached person id and name. If found, displays the name in the breadcrumb.
        /// Loads the questionnaire version and questionnaire answer, if any, and loads the questionnaire viewer control
        /// </summary>
        /// <param name="sender">Object that raised the event</param>
        /// <param name="e">Arguments associated with the event</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                string name = string.Empty;

                Hashtable incomingData = _pageCachePolicy.GetCachedObject(Keys.IncomingDataKey) as Hashtable;
                if (incomingData != null)
                {
                    if (incomingData.ContainsKey(Keys.FullNameKey))
                    {
                        name = Convert.ToString(incomingData[Keys.FullNameKey]);
                    }
                    if (incomingData.ContainsKey(Keys.ShowAsPopUp))
                    {
                        _showAsPopUp = Convert.ToBoolean(incomingData[Keys.ShowAsPopUp]);
                    }

                    _questionnaireVersionId = Convert.ToInt32(incomingData[Keys.QuestionnaireVersionIdKey]);
                    _questionnaireAnswerId = Convert.ToInt32(incomingData[Keys.QuesionnaireAnswerIdKey]);
                    _coiId = Convert.ToInt32(incomingData[Keys.COIIdKey]);
                }
                else
                {
                    throw new Exception("Page is being viewed out of context");
                }

                breadCrumb.Add(((name.Length > 0) ? string.Format("Disclosure Questionnaire - {0}", name) : "Disclosure Questionnaire"),
                    Settings.GetKeyValue("SubNavigation.CoI.AnswerChartURL", ""),
                    Settings.GetKeyValue("BreadCrumb.DetailPageLevel", 2));

                if (!Page.IsPostBack)
                {
                    // get the QuestionnaireVersion and Answer Ids.
                    QuestionnaireVersion questVersion = new QuestionnaireVersion(_cachePolicy);
                    questVersion.Load(DataAccess.GetConnectionString(), _questionnaireVersionId);
                    if (_questionnaireAnswerId == 0)
                    {
                        _questAnswer = new QuestionnaireAnswer(_cachePolicy);
                        _questAnswer.QuestionnaireVersionId = _questionnaireVersionId;
                        _questAnswer.Name = questVersion.Questionnaire.Name;
                    }
                    else
                    {
                        _questAnswer = new QuestionnaireAnswer(_cachePolicy);
                        _questAnswer.Load(DataAccess.GetConnectionString(), _questionnaireAnswerId);
                    }
                    CurrentConflictOfInterest.QuestionnaireAnswers.Clear();
                    CurrentConflictOfInterest.QuestionnaireAnswers.Add(_questAnswer);

                    questionnaireViewer.LoadQuestionnaire(questVersion, _questAnswer);

                    //name of the questionnaire
                    questionaireTitle.Text = questVersion.Questionnaire.Name;

                    imgbtnSaveTop.Attributes.Add("onClick", "javascript:return confirm('Use the \\'Continue Later\\' button only if you need to get additional information before completing this form. Otherwise, click Next.');");
                    imgbtnSaveBottom.Attributes.Add("onClick", "javascript:return confirm('Use the \\'Continue Later\\' button only if you need to get additional information before completing this form. Otherwise, click Next.');");
                }

                //if page is being shown as popup, then hide the header section
                headerSection.Visible = !_showAsPopUp;
                
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        #endregion

        #region Web Form Designer generated code

        /// <summary>
        /// Page Initialization
        /// </summary>
        /// <param name="e">Arguments associated with the event</param>
        protected override void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            base.OnInit(e);
            _cachePolicy = (Policy.ICachePolicy) Session[Policy.Names.CachePolicyKey];
            _pageCachePolicy = (Policy.ICachePolicy) Session[Policy.Names.PageCachePolicyKey];
            _applicationCachePolicy = (Policy.ICachePolicy) Application[Policy.Names.ApplicationCachePolicyKey];
        }

        #endregion

        #region Control events

        /// <summary>
        /// Updates the questionnaire answer with answers provided by the user.
        /// Runs the corresponding Requirement script which would update the COI object.
        /// Uncaches page specific details and redirects the user to the Overview page.
        /// </summary>
        /// <param name="sender">Object that raised the event</param>
        /// <param name="e">Arguments associated with the event</param>
        protected void OnSave(object sender, ImageClickEventArgs e)
        {
            try
            {
                SaveQuestionnaire();
                RunRequirementScript();
                UncacheIntraModuleNavigationDetails();
                ManageRedirection();
             }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Saves the questionnaire and validates the answers for errors
        /// </summary>
        /// <param name="sender">Object that raised the event</param>
        /// <param name="e">Arguments associated with the event</param>
        protected void OnSaveAndValidateClick(object sender, ImageClickEventArgs e)
        {
            try
            {
                SaveQuestionnaire();
                QuestionnaireVersion questVersion = new QuestionnaireVersion(_cachePolicy);
                questVersion.Load(DataAccess.GetConnectionString(), _questionnaireVersionId);
                _questAnswer = new QuestionnaireAnswer(_cachePolicy);
                _questAnswer.Load(DataAccess.GetConnectionString(), _questionnaireAnswerId);
                questionnaireViewer.LoadQuestionnaire(questVersion, _questAnswer);

                if (!questionnaireViewer.ValidateRequiredQuestions(true, string.Empty))
                {
                    imgbtnSaveTop.Visible = imgbtnSaveBottom.Visible = true;
                    return;
                }
                if (!questionnaireViewer.VerifyTextboxAnswers())
                {
                    imgbtnSaveTop.Visible = imgbtnSaveBottom.Visible = true;
                    return;
                }
                RunValidationScript(questionnaireViewer.Form);
                if (!questionnaireViewer.CheckForValidationErrors())
                {
                    questionnaireViewer.Refresh();
                    imgbtnSaveTop.Visible = imgbtnSaveBottom.Visible = true;
                    return;
                }

                RunRequirementScript();
                
                RefCodes refCodes = (RefCodes) _applicationCachePolicy.GetCachedObject(RefCodes.CacheKey);
                _questAnswer.Status = FormsManagement.Constants.QuestionnaireAnswerStatus.Completed;
                _questAnswer.StatusMeaning = refCodes.GetRefCode(FormsManagement.Constants.QuestionnaireAnswerStatus.Completed).Meaning;
                _questAnswer.Save(DataAccess.ConnectionString);

               


                UncacheIntraModuleNavigationDetails();

                ManageRedirection();
                
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }


        private void ManageRedirection()
        {
            if (_AlertOnChangesToReOpenedAnnualCOI)
            {
                string strClientScript = null;
                if (!_showAsPopUp)
                {
                    //AlertOnChangesToReOpenedAnnualCOI() -- can be moved to client side.

                    string strRedirectPage = Settings.GetKeyValue("SubNavigation.CoI.COIOverviewURL", "");
                    strRedirectPage = strRedirectPage.Substring(strRedirectPage.LastIndexOf("/")+1);
                    strClientScript = string.Format("alert('Please remember to make these updates to your Real Time Updates disclosure form');window.location.href='{0}';", strRedirectPage);
                    Page.ClientScript.RegisterStartupScript(GetType(), "AlertOnChangestoReopenedAnnualCOI", strClientScript, true);
                }
                else
                {
                    strClientScript = string.Format("alert('Please remember to make these updates to your Real Time Updates disclosure form');window.close();");
                    Page.ClientScript.RegisterClientScriptBlock(GetType(), "LogItem", strClientScript, true);
                }
            }
            else
            {
                if (!_showAsPopUp)
                {
                    Page.Response.Redirect(
                        Settings.GetKeyValue("SubNavigation.CoI.COIOverviewURL", ""), false);
                }
                else
                {
                    Page.ClientScript.RegisterClientScriptBlock(GetType(), "LogItem", "<script language='javascript'>window.close();</script>");
                }
            }
        }

        /// <summary>
        /// Resets the subnavigation selected link before the header or the breadCrumb performs a redirect.
        /// </summary>
        /// <param name="sender">Control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        protected void OnHeaderNavigate(object sender, CommandEventArgs e)
        {
            try
            {
                coiSubNavigation.Reset();
                coiSubModNavigation.Reset();
                UncacheInterModuleNavigationDetails();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Resets the subnavigation selected link before the breadCrumb performs a redirect.
        /// </summary>
        /// <param name="sender">Control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        protected void OnBreadCrumbNavigate(object sender, CommandEventArgs e)
        {
            try
            {
                coiSubModNavigation.Reset();
                UncacheCOIDetails();
                UncacheUserDetails();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Uncache all the details specific to the page
        /// </summary>
        /// <param name="sender">Object that raised the event</param>
        /// <param name="e">Arguments associated with the event</param>
        protected void OnCOISubModNavigationNavigate(object sender, CommandEventArgs e)
        {
            try
            {
                UncacheIntraModuleNavigationDetails();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Redirects the user to the COIOverview page after uncaching the page specific details
        /// </summary>
        /// <param name="sender">Object that raised the event</param>
        /// <param name="e">Arguments associated with the event</param>
        protected void OnCancel(object sender, ImageClickEventArgs e)
        {
            try
            {
                UncacheIntraModuleNavigationDetails();
                if (!_showAsPopUp)
                {
                    Response.Redirect(Settings.GetKeyValue("SubNavigation.CoI.COIOverviewURL", ""), false);
                }
                else
                {
                    Page.ClientScript.RegisterClientScriptBlock(GetType(), "LogItem", "<script language='javascript'>window.close();</script>");
                }
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        #endregion

        #region Private methods

        /// <summary>
        /// Execute the validation script
        /// </summary>
        private void RunValidationScript(Form form)
        {
            // Run the requirement script for the appropriate QuestionnaireVersion here.
            _questAnswer = (QuestionnaireAnswer) CurrentConflictOfInterest.QuestionnaireAnswers[0];
            QuestionnaireVersion version = _questAnswer.QuestionnaireVersion;

            Script validationScript =
                (Script) version.Scripts[FormsManagement.Constants.ScriptType.Validation];

            if (validationScript != null)
            {
                using (ScriptEngineHost scriptHost =
                    new ScriptEngineHost(
                        string.Format("{0}{1}", version.Id,
                            ScriptEngine.Constants.RootMoniker.ValidationScriptMoniker),
                        ScriptEngine.Constants.RootNamespaces.ValidationScript,
                        true))
                {
                    ArrayList refs = ScriptReference.GetAllScriptReferences(
                        DataAccess.GetConnectionString());

                    for (int i = 0; i < refs.Count; ++i)
                    {
                        ScriptReference reference = (ScriptReference) refs[i];
                        scriptHost.AddDLLReference(reference.Path);
                    }


                    // add the connection string
                    scriptHost.AddIntrinsicObject(ScriptEngine.Constants.Instrinsics.ConnectionString,
                        DataAccess.GetConnectionString());
                    // add the caching policy
                    scriptHost.AddIntrinsicObject(ScriptEngine.Constants.Instrinsics.CachePolicy, _cachePolicy);
                    // add this COI as an intrinsic.
                    scriptHost.AddIntrinsicObject(ScriptEngine.Constants.Instrinsics.COI, CurrentConflictOfInterest);
                    // add the QuestionnaireAnswer
                    scriptHost.AddIntrinsicObject(ScriptEngine.Constants.Instrinsics.QuestionnaireAnswer,
                        _questAnswer);
                    // add the QuestionnaireAnswer
                    scriptHost.AddIntrinsicObject(ScriptEngine.Constants.Instrinsics.Form,
                        form);

                    // compile and run the script.
                    if (scriptHost.Compile(validationScript))
                    {
                        scriptHost.RunScript(validationScript,
                            ScriptEngine.Constants.AssemblyType.ValidationScript,
                            ScriptEngine.Constants.MethodsToRun.Main);
                    }
                }
            }
        }

        /// <summary>
        /// Execute the requirement script
        /// </summary>
        private void RunRequirementScript()
        {
            // Run the requirement script for the appropriate QuestionnaireVersion here.
            _questAnswer = (QuestionnaireAnswer) CurrentConflictOfInterest.QuestionnaireAnswers[0];
            QuestionnaireVersion version = _questAnswer.QuestionnaireVersion;

            Script requirementScript =
                (Script) version.Scripts[FormsManagement.Constants.ScriptType.Requirement];

            if (requirementScript != null)
            {
                using (ScriptEngineHost scriptHost =
                    new ScriptEngineHost(
                        string.Format("{0}{1}", version.Id,
                            ScriptEngine.Constants.RootMoniker.RequirementScriptMoniker),
                        ScriptEngine.Constants.RootNamespaces.RequirementScript,
                        true))
                {
                    ArrayList refs = ScriptReference.GetAllScriptReferences(
                        DataAccess.GetConnectionString());

                    for (int i = 0; i < refs.Count; ++i)
                    {
                        ScriptReference reference = (ScriptReference) refs[i];
                        scriptHost.AddDLLReference(reference.Path);
                    }


                    // add the connection string
                    scriptHost.AddIntrinsicObject(ScriptEngine.Constants.Instrinsics.ConnectionString,
                        DataAccess.GetConnectionString());
                    // add the caching policy
                    scriptHost.AddIntrinsicObject(ScriptEngine.Constants.Instrinsics.CachePolicy, _cachePolicy);
                    // add this COI as an intrinsic.
                    scriptHost.AddIntrinsicObject(ScriptEngine.Constants.Instrinsics.COI, CurrentConflictOfInterest);
                    // add the QuestionnaireAnswer
                    scriptHost.AddIntrinsicObject(ScriptEngine.Constants.Instrinsics.QuestionnaireAnswer,
                        _questAnswer);
                    // add the questionnaireversionid

                    // compile and run the script.
                    if (scriptHost.Compile(requirementScript))
                    {
                        scriptHost.RunScript(requirementScript,
                            ScriptEngine.Constants.AssemblyType.RequirementScript,
                            ScriptEngine.Constants.MethodsToRun.Main);
                    }
                }
            }
        }

        /// <summary>
        /// Save the answers provided by the user
        /// </summary>
        private void SaveQuestionnaire()
        {
            _questAnswer = (QuestionnaireAnswer) CurrentConflictOfInterest.QuestionnaireAnswers[0];
            _questAnswer.UpdateModifiedDate = true;
            RefCodes refCodes = (RefCodes) _applicationCachePolicy.GetCachedObject(RefCodes.CacheKey);
            _questAnswer.Status = FormsManagement.Constants.QuestionnaireAnswerStatus.InProgress;
            _questAnswer.StatusMeaning = refCodes.GetRefCode(FormsManagement.Constants.QuestionnaireAnswerStatus.InProgress).Meaning;

            // grab the list of questions from the Forms control, and save them as appropriate
            //if (!questionnaireViewer.VerifyTextboxAnswers())
            //    return;
            questionnaireViewer.SaveQuestionnaire(_questAnswer);
            CurrentConflictOfInterest.Status = Constants.COIStatus.InProgress;
            if (CurrentConflictOfInterest.COIType == (int)Constants.COIType.RealTimeUpdate)
            {
                //To force the creation of the Report.
                CurrentConflictOfInterest.DateSubmitted = DateTime.MinValue;
                if (null != CurrentConflictOfInterest.Report)
                {
                    CurrentConflictOfInterest.Report.Delete(DataAccess.ConnectionString);
                    CurrentConflictOfInterest.DocumentId = 0;
                }
               
                CurrentConflictOfInterest.Save(DataAccess.ConnectionString, Constants.COIDateType.SubmittedDate, Server.MapPath(""));
                //Audit anytime a RTU COI is saved.
                CurrentConflictOfInterest.AuditCOIChanges(Constants.COIActionsForAudit.QuestionnaireUpdated + _questAnswer.Name);
            }
            else if (CurrentConflictOfInterest.COIType == (int)Constants.COIType.AnnualCycle)
            {
                CurrentConflictOfInterest.Save(DataAccess.GetConnectionString());
            }

            if (CurrentConflictOfInterest.COIType == (int)Constants.COIType.AnnualCycle && CurrentConflictOfInterest.IsCOIReOpened)
            {
                _AlertOnChangesToReOpenedAnnualCOI = true;
            }
        }

        /// <summary>
        /// Displays an error message on the screen to the user with the exception, and all
        /// inner exception messages.
        /// </summary>
        /// <param name="ex">The exception to report on</param>
        private void DisplayExceptionReport(Exception ex)
        {
            annunciator.Title = InsightUtilities.Constants.Annunciator.Title;
            annunciator.Message = ExceptionReport.GetExceptionInfo(ex, false);
        }

        /// <summary>
        /// Removes all the details that are specific to the COI Module from cache
        /// </summary>
        private void UncacheInterModuleNavigationDetails()
        {
            Hashtable incomingData = _pageCachePolicy.GetCachedObject(Keys.IncomingDataKey) as Hashtable;
            if (incomingData != null)
            {
                if (incomingData.ContainsKey(Keys.ShowAsPopUp))
                {
                    incomingData.Remove(Keys.ShowAsPopUp);
                }

                incomingData.Remove(Keys.QuesionnaireAnswerIdKey);
                incomingData.Remove(Keys.QuestionnaireVersionIdKey);
            }
            UncacheCOIDetails();
            UncacheUserDetails();
        }

        /// <summary>
        /// Uncache COI
        /// </summary>
        private void UncacheCOIDetails()
        {
            Hashtable incomingData = _pageCachePolicy.GetCachedObject(Keys.IncomingDataKey) as Hashtable;
            if (incomingData != null)
            {
                incomingData.Remove(Keys.COIIdKey);
            }
            _coi = _cachePolicy.GetCachedObject(ConflictOfInterest.COIKey) as ConflictOfInterest;
            if (_coi != null)
            {
                _coi.UnCache();
            }
        }

        /// <summary>
        /// Removes all the details specific to the page from cache
        /// </summary>
        private void UncacheIntraModuleNavigationDetails()
        {
            Hashtable incomingData = _pageCachePolicy.GetCachedObject(Keys.IncomingDataKey) as Hashtable;
            if (incomingData != null)
            {
                incomingData.Remove(Keys.QuesionnaireAnswerIdKey);
                incomingData.Remove(Keys.QuestionnaireVersionIdKey);
            }
        }

        /// <summary>
        /// Remove the fwkdomainuserid and the username, if exists, from the cache
        /// </summary>
        private void UncacheUserDetails()
        {
            Hashtable incomingData = _pageCachePolicy.GetCachedObject(Keys.IncomingDataKey) as Hashtable;
            if (incomingData != null)
            {
                if (incomingData.ContainsKey(Keys.FullNameKey))
                {
                    incomingData.Remove(Keys.FullNameKey);
                }
                if (incomingData.ContainsKey(Keys.AdmPersonIdKey))
                {
                    incomingData.Remove(Keys.AdmPersonIdKey);
                }
            }
        }

        #endregion


        #region Test vb scripts
        /*

        private void TestVBS_TrusteeeDisclosure()
        {
            ArrayList answers;
            QuestionnaireAnswer questAnswer = (QuestionnaireAnswer) CurrentConflictOfInterest.QuestionnaireAnswers[0];
            QuestionnaireVersion version = questAnswer.QuestionnaireVersion;

            answers = questAnswer.GetAnswers("YourEquityInterests");//YourAssociations

            ArrayList answers1;
            answers1 = questAnswer.GetAnswers("YourAssociations");

            Answer answer;
            Answer answer1;
		    if(answers.Count > 0 || answers1.Count > 0)
            {
			    answer = answers.Count > 0 ? (Answer)answers[0] : new Answer(_cachePolicy);
                answer1 = answers1.Count > 0 ? (Answer)answers1[0] : new Answer(_cachePolicy);

			    if(answer.Value == "Y" || answer1.Value == "Y") 
                {
			   	    CurrentConflictOfInterest.HasEquityInterests = 'Y';
				    //Get the active questionnaireversion no.
				    QuestionnaireVersion equityInterestQV = Questionnaire.GetActiveVersion(_cachePolicy,"Trustee Association",PHSRAG.Insight21.FormsManagement.Constants.QuestionnaireType.COI);

                    answers = questAnswer.GetAnswers("ListEquityInterests");//ListAssociations
                    answers1 = questAnswer.GetAnswers("ListAssociations");

                    //Club the two array lists
                    foreach (Answer A in answers1)
                    {
                        if (!answers.Contains(A))
                        {
                            answers.Add(A);
                        }

                    }

				    //Delete the EI which are no longer applicable
                    foreach(QuestionnaireAnswer QA in CurrentConflictOfInterest.QuestionnaireAnswers)
                    {
                        if(QA.QuestionnaireCategory == "QUESTCAT_COI_EI" && QA.QuestionnaireVersion.Questionnaire.Name == "Trustee Association")
                        {
                            bool found = false;
                            foreach(Answer A in answers)
                            {   string[] ei = A.Value.Split(new char[]{'|'});
                                if(QA.Name == ei[1])
                                {
                                    found = true;
                                    break;
                                }
                            }
                            if(!found)
                            {
                                CurrentConflictOfInterest.RemoveQuestionnaireAnswer(QA.Id);
                            }
                        }
                    }
				   
					//Adding to Qusetionnaire Answers
                    foreach(Answer A in answers)
                    {
                        string [] ei = A.Value.Split(new char[]{'|'});
                        bool found = false;
                        //Add QA if its no yet added.
                        foreach(QuestionnaireAnswer QA in CurrentConflictOfInterest.QuestionnaireAnswers)
                        {
                            if(QA.QuestionnaireCategory == "QUESTCAT_COI_EI" && QA.QuestionnaireVersion.Questionnaire.Name == "Trustee Association")
                            {
                                if(QA.Name == ei[1])
                                {
                                    found = true;
                                    break;
                                }
                            }
                        }
                        if(!found)
                        {
                            QuestionnaireAnswer QA = new QuestionnaireAnswer(_cachePolicy);
                            QA.QuestionnaireVersionId = equityInterestQV.Id;
                            QA.Name = ei[1];
                            QA.ExternalId = Convert.ToInt32(ei[0].ToString());

                            Answer OutsideEntityAnswer = new Answer(_cachePolicy);
                            OutsideEntityAnswer.QuestionnaireAnswerId = QA.Id;
                            OutsideEntityAnswer.Name = "OutsideEntityName";
                            OutsideEntityAnswer.Value = ei[1];

                            QA.Answers.Add(OutsideEntityAnswer);
                            CurrentConflictOfInterest.QuestionnaireAnswers.Add(QA);
                            CurrentConflictOfInterest.Save(DataAccess.ConnectionString);//'takes care of the mapping record

                        }

                    }
                }
			    else
                {
			       CurrentConflictOfInterest.HasEquityInterests = 'N';
                    foreach(QuestionnaireAnswer QA in CurrentConflictOfInterest.QuestionnaireAnswers)
                    {
                        if (QA.QuestionnaireCategory == "QUESTCAT_COI_EI" && QA.QuestionnaireVersion.Questionnaire.Name == "Trustee Association")
                        {
                            CurrentConflictOfInterest.RemoveQuestionnaireAnswer(QA.Id);
			            }
                    }

			       
                }
			    
			    }						
         }


        private void TestVBS_TrusteeeDisclosure_old()
        {
            ArrayList answers;
            QuestionnaireAnswer questAnswer = (QuestionnaireAnswer)CurrentConflictOfInterest.QuestionnaireAnswers[0];
            QuestionnaireVersion version = questAnswer.QuestionnaireVersion;

            answers = questAnswer.GetAnswers("YourEquityInterests");//YourAssociations

            Answer answer;
            if (answers.Count > 0)
            {
                answer = (Answer)answers[0];

                if (answer.Value == "Y")
                {
                    CurrentConflictOfInterest.HasEquityInterests = 'Y';
                    //Get the active questionnaireversion no.
                    QuestionnaireVersion equityInterestQV = Questionnaire.GetActiveVersion(_cachePolicy, "Trustee Association", PHSRAG.Insight21.FormsManagement.Constants.QuestionnaireType.COI);

                    answers = questAnswer.GetAnswers("ListEquityInterests");//ListYourAssociations

                    //Delete the EI which are no longer applicable
                    foreach (QuestionnaireAnswer QA in CurrentConflictOfInterest.QuestionnaireAnswers)
                    {
                        if (QA.QuestionnaireCategory == "QUESTCAT_COI_EI" && QA.QuestionnaireVersion.Questionnaire.Name == "Trustee Association")
                        {
                            bool found = false;
                            foreach (Answer A in answers)
                            {
                                string[] ei = A.Value.Split(new char[] { '|' });
                                if (QA.Name == ei[1])
                                {
                                    found = true;
                                    break;
                                }
                            }
                            if (!found)
                            {
                                CurrentConflictOfInterest.RemoveQuestionnaireAnswer(QA.Id);
                            }
                        }
                    }

                    //Adding to Qusetionnaire Answers
                    foreach (Answer A in answers)
                    {
                        string[] ei = A.Value.Split(new char[] { '|' });
                        bool found = false;
                        //Add QA if its no yet added.
                        foreach (QuestionnaireAnswer QA in CurrentConflictOfInterest.QuestionnaireAnswers)
                        {
                            if (QA.QuestionnaireCategory == "QUESTCAT_COI_EI" && QA.QuestionnaireVersion.Questionnaire.Name == "Trustee Association")
                            {
                                if (QA.Name == ei[1])
                                {
                                    found = true;
                                    break;
                                }
                            }
                        }
                        if (!found)
                        {
                            QuestionnaireAnswer QA = new QuestionnaireAnswer(_cachePolicy);
                            QA.QuestionnaireVersionId = equityInterestQV.Id;
                            QA.Name = ei[1];
                            QA.ExternalId = Convert.ToInt32(ei[0].ToString());

                            Answer OutsideEntityAnswer = new Answer(_cachePolicy);
                            OutsideEntityAnswer.QuestionnaireAnswerId = QA.Id;
                            OutsideEntityAnswer.Name = "OutsideEntityName";
                            OutsideEntityAnswer.Value = ei[1];

                            QA.Answers.Add(OutsideEntityAnswer);
                            CurrentConflictOfInterest.QuestionnaireAnswers.Add(QA);
                            CurrentConflictOfInterest.Save(DataAccess.ConnectionString);//'takes care of the mapping record

                        }

                    }
                }
                else
                {
                    CurrentConflictOfInterest.HasEquityInterests = 'N';
                    foreach (QuestionnaireAnswer QA in CurrentConflictOfInterest.QuestionnaireAnswers)
                    {
                        if (QA.QuestionnaireCategory == "QUESTCAT_COI_EI" && QA.QuestionnaireVersion.Questionnaire.Name == "Trustee Association")
                        {
                            CurrentConflictOfInterest.RemoveQuestionnaireAnswer(QA.Id);
                        }
                    }


                }

            }
        }

        */
        #endregion Test vb scripts
    }
}